package com.dearbinge.web.user.controller;

import com.dearbinge.data.api.ofUser.OfUserService;
import com.dearbinge.data.api.user.UserService;
import com.dearbinge.data.pojo.ofuser.Ofuser;
import com.dearbinge.data.pojo.user.User;
import com.dearbinge.data.redis.service.RedisService;
import com.dearbinge.utils.Base64Util;
import com.dearbinge.utils.Constants;
import com.dearbinge.utils.CookieUtils;
import com.dearbinge.utils.ResultMsg;
import com.dearbinge.utils.httpClient.UrlValidUtil;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@SuppressWarnings("all")
@RestController
@RequestMapping("/user")
//@ImportResource({ "classpath:applicationContext.xml", "dubbo-services.xml" })
@EnableAutoConfiguration
public class UserController extends WebMvcConfigurerAdapter {

	@Autowired
	private RedisService redisService;

	@Autowired
	private UserService userService;


	@Autowired
	private OfUserService ofUserService;

	/**
	 * 苹果审核前返回true  审核通过返回false
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/auditStatus", method = RequestMethod.GET)
	public ResultMsg<String> auditStatus() {
		String status = "true";
		try {
			ResultMsg.okMsg(status);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMsg.okMsg(status);
		}
		return ResultMsg.okMsg(status);
	}




	/**
	 * 退出注销登录用户
	 * @param opendi 微信openid
	 * @return
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ResultMsg<String> logout(String openid) {
		try {
			redisService.del(Constants.TOKEN_USER_REDIS_KEY+":"+openid);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMsg.error(500, "error");
		}
		return ResultMsg.ok("ok");
	}


	/**
	 * 测试返回自增ID    自增id只能在service层获取到
	 * <insert id="insert" keyProperty="id" useGeneratedKeys="true"  parameterType="com.demo.domain.User"> 
	 * @return
	 */

	public ResultMsg<String> testUserId() {
		try {
			User user = new User();//保存用戶表要的數據
			user.setHeadImg("asdfasdf");
			Integer insert = userService.insert(user);
			System.out.println("UserId======" + insert);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMsg.error(500, "error");
		}
		return ResultMsg.ok("ok");
	}


	@ApiOperation(value = "测试url加密", notes = "测试url加密")
	@RequestMapping(value = "/testUrlValid", method = RequestMethod.GET)
	public ResultMsg<String> testUrlValid(String sign,
			HttpServletRequest request) {
		try {
			boolean urlValid = UrlValidUtil.urlValid(sign, "token", request);
			System.out.println("urlValid======" + urlValid);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMsg.error(500, "error");
		}
		return ResultMsg.ok("ok");
	}


	/**
	 * app授权获取微信用户信息
	 * @param code
	 * @param unionid
	 * @param request
	 * @param responses
	 * @return
	 */
	@RequestMapping(value = "/getAccessToken", method = RequestMethod.GET)
	public ResultMsg<User> getAccessToken(String code, String unionid,HttpServletRequest request, HttpServletResponse responses) {
		try {
			Thread.currentThread().sleep(2000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}//毫秒
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
				+ Constants.appid + "&secret=" + Constants.AppSecret + "&code=" + code
				+ "&grant_type=authorization_code";
		URI uri = URI.create(url);
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(uri);

		HttpResponse response;
		User user = new User();//保存用戶表要的數據
		try {
			response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(entity.getContent(), "UTF-8"));
				StringBuilder sb = new StringBuilder();

				for (String temp = reader.readLine(); temp != null; temp = reader
						.readLine()) {
					sb.append(temp);
				}

				JSONObject object = JSONObject.fromObject((Object) sb
						.toString().trim());
				String accessToken = object.getString("access_token");
				String openID = object.getString("openid");
				String refreshToken = object.getString("refresh_token");
				Long expires_in = object.getLong("expires_in");


				user.setOpendId(openID);
				getUserInfo(accessToken, expires_in, openID,user);
				User byOpendId = userService.getByOpendId(openID);
				if(StringUtils.isEmpty(byOpendId)){
					Integer insert = userService.insert(user);
					user.setId(insert);
				}else{
					user.setId(byOpendId.getId());
					user.setName(null);
					Integer update = userService.update(user);
				}

				//ofUserService  用户插入openfire
				Ofuser ofuser = new Ofuser();
				ofuser.setUsername(String.valueOf(user.getId()));
				ofuser.setPlainpassword("123456");
				Integer insert = ofUserService.insert(ofuser);
				System.out.println("ofUserService  用户插入openfire结果==="+insert);

				Map map = new HashMap<String, String>();
				String token = UUID.randomUUID() + ":" + user.getOpendId();
				CookieUtils.setCookie(request, responses,Constants.TOKEN_USER_REDIS_KEY, token);
				map.put("userObject", user.toString());
				map.put("token", token);
				map.put("refreshToken", refreshToken);
				redisService.hmset(Constants.TOKEN_USER_REDIS_KEY+":"+user.getOpendId(), map);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMsg.error(500, "error");
		}
		return ResultMsg.ok(user);
	}


	private void getUserInfo(String accessToken, Long expires_in, String openID,User user) {
//		if (isAccessTokenIsInvalid(accessToken, openID)&& System.currentTimeMillis() < expires_in) {
			String uri = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN&access_token="
					+ accessToken + "&openid=" + openID;
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URI.create(uri));
			try {
				HttpResponse response = client.execute(get);
				if (response.getStatusLine().getStatusCode() == 200) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(response.getEntity()
									.getContent(), "UTF-8"));
					StringBuilder builder = new StringBuilder();
					for (String temp = reader.readLine(); temp != null; temp = reader
							.readLine()) {
						builder.append(temp);
					}
					JSONObject object = JSONObject.fromObject((Object) builder
							.toString().trim());
					user.setByname(object.getString("nickname"));
					user.setName(object.getString("nickname"));
					if("1".equals(object.getString("sex"))){
						user.setSex(true);
					}else{
						user.setSex(false);
					}
					user.setDistrict(object.getString("country")+","+object.getString("province")+","+object.getString("city"));
					user.setHeadImg(object.getString("headimgurl"));
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//		}
	}

	private boolean isAccessTokenIsInvalid(String accessToken, String openID) {
		String url = "https://api.weixin.qq.com/sns/auth?access_token="
				+ accessToken + "&openid=" + openID;
		URI uri = URI.create(url);
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(uri);
		HttpResponse response;
		try {
			response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(entity.getContent(), "UTF-8"));
				StringBuilder sb = new StringBuilder();

				for (String temp = reader.readLine(); temp != null; temp = reader
						.readLine()) {
					sb.append(temp);
				}
				JSONObject object = JSONObject.fromObject((Object) sb
						.toString().trim());
				int errorCode = object.getInt("errcode");
				if (errorCode == 0) {
					return true;
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	private void refreshAccessToken(String refreshToken, String APP_ID) {
		String uri = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="
				+ APP_ID
				+ "&grant_type=refresh_token&refresh_token="
				+ refreshToken;
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(URI.create(uri));
		try {
			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(
								response.getEntity().getContent(), "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String temp = reader.readLine(); temp != null; temp = reader
						.readLine()) {
					builder.append(temp);
				}
				JSONObject object = JSONObject.fromObject((Object) builder
						.toString().trim());
				String accessToken = object.getString("access_token");
				refreshToken = object.getString("refresh_token");
				String openID = object.getString("openid");
				Long expires_in = object.getLong("expires_in");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
